package com.ma5d.driver.driver.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.codec.Base64;
import com.ma5d.driver.common.exception.DriverException;
import com.ma5d.driver.common.result.ResultCodeEnum;
import com.ma5d.driver.driver.service.CosService;
import com.ma5d.driver.driver.service.OcrService;
import com.ma5d.driver.model.vo.driver.CosUploadVo;
import com.ma5d.driver.model.vo.driver.DriverLicenseOcrVo;
import com.ma5d.driver.model.vo.driver.IdCardOcrVo;
import com.ma5d.driver.driver.properties.TencentProperties;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.DriverLicenseOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.DriverLicenseOCRResponse;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRResponse;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Service
public class OcrServiceImpl implements OcrService {

    @Resource
    private TencentProperties tencentProperties;

    @Resource
    private CosService cosService;


    public IdCardOcrVo idCardOcr(MultipartFile file) {
        try {
            byte[] base64 = Base64.encodeBase64(file.getBytes());
            String fileBase64 = new String(base64);
            Credential credential = new Credential(tencentProperties.getSecretId(), tencentProperties.getSecretKey());
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            // TODO 应该启动的时候注入
            OcrClient ocrClient = new OcrClient(credential, tencentProperties.getRegion(), clientProfile);
            IDCardOCRRequest request = new IDCardOCRRequest();
            request.setImageBase64(fileBase64);
            // IDCardOCRResponse response = ocrClient.IDCardOCR(request);
            // language=json
            String frontResponseJson = """
                    {
                      "Address": "天府省地狱县安居乡乐业村108号",
                      "AdvancedInfo": "{}",
                      "Authority": "",
                      "Birth": "2024-12-15",
                      "IdNum": "123456202412151234",
                      "Name": "云天叶",
                      "Nation": "汉",
                      "RequestId": "2e3b7973-9a57-4be9-babc-3fcc089cd70e",
                      "Sex": "男",
                      "ValidDate": ""
                    }
                    """;

            // language=json
            String backResponseJSON = """
                    {
                      "Address": "",
                      "AdvancedInfo": "{}",
                      "Authority": "地狱公安局",
                      "Birth": "",
                      "IdNum": "",
                      "Name": "",
                      "Nation": "",
                      "RequestId": "a82b6122-2c75-4688-ae6a-c12864363a98",
                      "Sex": "",
                      "ValidDate": "2024.12.15-2034.12.15"
                    }
                    """;

            String requestJSON = """
                    {
                      "Address": "天府省地狱县安居乡乐业村108号",
                      "AdvancedInfo": "{}",
                      "Authority": "地狱公安局",
                      "Birth": "2024\\/12\\/15",
                      "IdNum": "123456202412151234",
                      "Name": "云天叶",
                      "Nation": "汉",
                      "RequestId": "2e3b7973-9a57-4be9-babc-3fcc089cd70e",
                      "Sex": "男",
                      "ValidDate": "2024\\.12\\.15-2034\\.12\\.15"
                    }
                    """;

            IDCardOCRResponse response = JSON.parseObject(requestJSON, IDCardOCRResponse.class);
            IdCardOcrVo idCardOcrVo = new IdCardOcrVo();
            // if (StringUtils.hasText(response.getName())) {
            idCardOcrVo.setName(response.getName());
            idCardOcrVo.setGender("男".equals(response.getSex()) ? "1" : "2");
            idCardOcrVo.setBirthday(LocalDate.parse(response.getBirth(), DateTimeFormatter.ofPattern("yyyy/MM/dd")));
            idCardOcrVo.setIdCardNo(response.getIdNum());
            idCardOcrVo.setIdCardAddress(response.getAddress());

            CosUploadVo cosUploadVo = cosService.upload(file, "idCard");
            idCardOcrVo.setIdCardFrontUrl(cosUploadVo.getUrl());
            idCardOcrVo.setIdCardFrontShowUrl(cosUploadVo.getShowUrl());
            // }else{
            // 身份证反面
            String idCardExpireString = response.getValidDate().split("-")[1];
            idCardOcrVo.setIdCardExpire(LocalDate.parse(idCardExpireString, DateTimeFormatter.ofPattern("yyyy.MM.dd")));

            // CosUploadVo cosUploadVo = cosService.upload(file, "idCard");
            idCardOcrVo.setIdCardBackUrl(cosUploadVo.getUrl());
            idCardOcrVo.setIdCardBackShowUrl(cosUploadVo.getShowUrl());
            // }
            return idCardOcrVo;
        } catch (Exception e) {
            e.printStackTrace();
            throw new DriverException(ResultCodeEnum.DATA_ERROR);
        }
    }

    @Override
    public DriverLicenseOcrVo driverLicenseOcr(MultipartFile file) {
        try {
            // 图片转换 base64 格式字符串
            byte[] base64 = Base64.encodeBase64(file.getBytes());
            String fileBase64 = new String(base64, StandardCharsets.UTF_8);

            Credential credential = new Credential(tencentProperties.getSecretId(), tencentProperties.getSecretKey());
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            OcrClient ocrClient = new OcrClient(credential, tencentProperties.getRegion(), clientProfile);
            DriverLicenseOCRRequest request = new DriverLicenseOCRRequest();
            request.setImageBase64(fileBase64);
            // region DriverLicenseOCRResponse response = ocrClient.DriverLicenseOCR(request);
            DriverLicenseOCRResponse response = new DriverLicenseOCRResponse();
            response.setName("云天叶");
            response.setDateOfFirstIssue("2024-12-15");
            response.setEndDate("2034-12-15");
            response.setRequestId("2e3b7973-9a57-4be9-babc-3fcc089cd70e");
            // endregion

            DriverLicenseOcrVo driverLicenseOcrVo = new DriverLicenseOcrVo();
            if(StringUtils.hasText(response.getName())){
                driverLicenseOcrVo.setName(response.getName());
                driverLicenseOcrVo.setDriverLicenseClazz(response.getClass_());
                driverLicenseOcrVo.setDriverLicenseNo(response.getCardCode());
                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                driverLicenseOcrVo.setDriverLicenseIssueDate(LocalDate.parse(response.getDateOfFirstIssue(), dtf));
                driverLicenseOcrVo.setDriverLicenseExpire(LocalDate.parse(response.getEndDate(), dtf));

                CosUploadVo cosUploadVo = cosService.upload(file, "driverLicense");
                driverLicenseOcrVo.setDriverLicenseFrontUrl(cosUploadVo.getUrl());
                driverLicenseOcrVo.setDriverLicenseFrontShowUrl(cosUploadVo.getShowUrl());
            } else {
                CosUploadVo cosUploadVo = cosService.upload(file, "driverLicense");
                driverLicenseOcrVo.setDriverLicenseFrontUrl(cosUploadVo.getUrl());
                driverLicenseOcrVo.setDriverLicenseFrontShowUrl(cosUploadVo.getShowUrl());
            }
        return driverLicenseOcrVo;
        } catch (Exception e) {
            e.printStackTrace();
            throw new DriverException(ResultCodeEnum.DATA_ERROR);
        }
    }
}
